const { SYSTEM } = chrome.proxy.Mode;
import { DATA_LIST, ENABLE_PROXY } from "../constants.js";

export default class ProxyManager {
	constructor() {
		this._dataList = null;
		this._storageSync = chrome.storage.sync;

		this.getDataList().then(({ dataList }) => {
			this._dataList = dataList;
		});
	}

	getDataList() {
		return this._storageSync.get(DATA_LIST);
	}

	insertProxy(data) {
		if (!data) {
			return;
		}

		this._dataList.unshift(data);

		this._reload();
	}

	getProxy(id) {
		return this._dataList.find((data) => data.id === id);
	}

	enableProxy(id) {
		const oldEnableObj = this._dataList.find((data) => data.isUsed);
		const newEnableObj = this._dataList.find((data) => data.id === id);

		if (oldEnableObj) {
			oldEnableObj.isUsed = false;
		}

		newEnableObj.isUsed = true;

		this._storageSync.set({ enableProxy: newEnableObj });

		this._reload();
	}

	updateProxy(id, part) {
		const dataObj = this._dataList.find((data) => data.id === id);
		Object.assign(dataObj, part);

		if (dataObj.isUsed) {
			this._storageSync.set({ enableProxy: dataObj });
		}

		this._storageSync.set({ dataList: this._dataList });
	}

	deleteProxy(id) {
		const dataObjIndex = this._dataList.findIndex((data) => data.id === id);
		const dataObj = this._dataList[dataObjIndex];

		this._dataList.splice(dataObjIndex, 1);

		if (dataObj.isUsed) {
			this._storageSync.remove(ENABLE_PROXY);
			// 没有任何代理配置 切回系统代理
			this._storageSync.set({ mode: SYSTEM });
		}

		this._reload();
	}

	_reload() {
		this._dataList.sort((a, b) => {
			if (a.isUsed) {
				return -1;
			}

			if (b.isUsed) {
				return 1;
			}

			return 0;
		});
		this._storageSync.set({ dataList: this._dataList });
	}
}
